<template>
  <div class="question-box">
    <div class="question-main">
      <!-- 答题卡 -->
      <div class="question-sub-box">
        <div class="s-title">答题卡</div>
        <div class="sub-box_con">
          <ul class="ul-box">
            <li v-for="(item, index) in questionData" :key="index" :class="{ selected: isCheck(item.checkIds) }">
              <a :href="`#formItem${index}`">{{ index + 1 }}</a>
            </li>
          </ul>
          <div class="total">
            已完成<span> {{ selectQuestion }} </span>道题，共<span> {{ questionData.length }} </span>道题
          </div>
          <el-button
            type="primary"
            class="submit-que"
            @click="subQuestion"
            :disabled="!(status.includes(data.status) && data.admin == '1')"
            >提交问卷</el-button
          >
        </div>
      </div>
      <!-- 问卷内容 -->
      <div class="question-con">
        <div class="title">{{ data.domain }}（{{ data.domainName }}） 审计指标设定（调查问卷）</div>
        <el-form
          :model="ruleForm"
          label-position="top"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="ruleForm"
        >
          <span v-for="(item, index) in questionData" :key="index">
            <!-- <span class="sign">{{ index + 1 }}.</span> -->
            <el-form-item :prop="item.sceneId" v-if="item.options === 'checkbox'" :id="`formItem${index}`">
              <span slot="label">{{ index + 1 }}、{{ item.question }}</span>
              <el-checkbox-group v-model="ruleForm[item.sceneId]" @change="checkboxChange(item.sceneId)">
                <el-checkbox :label="check.id" v-for="(check, i) in item.optionNames" :key="i">{{
                  check.optionName
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :prop="item.sceneId" v-if="item.options === 'radio'" :id="`formItem${index}`">
              <span slot="label">{{ index + 1 }}、{{ item.question }}</span>
              <el-radio-group v-model="ruleForm[item.sceneId]" @change="radioChange(item.sceneId)">
                <el-radio :label="check.id" v-for="(check, i) in item.optionNames" :key="i">{{
                  check.optionName
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </span>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getQuestionsApi, saveQuestionsApi } from "api/evaluateApi";
import secQuestion from "components/questionnaire/index.vue";
export default {
  name: "questionnaire",
  props: {},
  components: {},
  data() {
    return {
      status: ["12", "13"],
      query: {},
      // selectQuestion: 0, //已经做了几道题
      data: {},
      questionData: [], //调查问卷界面展示题目的数据
      ruleForm: {},
      rules: {},
    };
  },
  computed: {
    /**
     * @函数功能:在答题卡 实现已完成多少道题的联动
     * @参数输入:
     * @函数返回:
     */
    selectQuestion() {
      let selectNum = 0;
      this.questionData.forEach((item) => {
        if (this.isCheck(item.checkIds)) {
          selectNum++;
        }
      });
      return selectNum;
    },
  },
  mounted() {
    // let questionData = JSON.parse(window.sessionStorage.getItem("questionData"));
    this.query = this.$route.query;
    // this.questionData = questionData || this.data.data;
    // this.questionData = this.data.data;
    getQuestionsApi({ reportId: this.$route.query.reportId }).then((res) => {
      console.log(res);
      this.data = res.data;
      this.questionData = this.data.questions;
      console.log(this.questionData);
      this.getQuestion();
    });
  },
  methods: {
    checkboxChange(sceneId) {
      this.setQuestionData(sceneId);
    },
    radioChange(sceneId) {
      this.setQuestionData(sceneId);
    },
    /**
     * @函数功能:把选中的值 赋值给questionData 里面的 check字段里面
     * @参数输入:
     * @函数返回:
     */
    setQuestionData(sceneId) {
      this.questionData.forEach((item, index) => {
        //兼容之前添加了（序号、） 现在需要去除 实现传给后台的时候question也不带着（序号、） 现在是直接在html中加这个序号、了
        item.question = item.question.slice(item.question.indexOf("、") + 1);
        if (item.sceneId == sceneId) {
          if (item.options === "radio") {
            item.checkIds = [];
            item["checkIds"].push(this.ruleForm[sceneId]);
          } else if (item.options === "checkbox") {
            item["checkIds"] = this.ruleForm[sceneId];
          }
        }
      });
      this.data.questions = this.questionData;
      // window.sessionStorage.setItem("questionData", JSON.stringify(this.data)); //本地存储一份
    },
    /**
     * @函数功能:根据复选框和单选框 是否选中
     * @参数输入:checkIds(里面放的是optionNames.id的值) 复选框是数组 单选框是字符串
     * @函数返回:选中返回true 否则false
     */
    isCheck(checkIds) {
      if (Array.isArray(checkIds)) {
        return checkIds.length > 0 || false;
      }
      return checkIds || false;
    },
    getQuestion() {
      let form = {}; //解决vue 不触发视图更新 把一些对象先赋值到这个对象上，然后在把整个对象赋值给ruleForm
      let rules = {};
      //有标题但是没有选项的筛选掉
      this.questionData = this.questionData.filter((item) => {
        return item.optionNames.length > 0;
      });
      this.questionData.forEach((item, index) => {
        if (item.options === "checkbox") {
          form[item.sceneId] = item.checkIds || [];
        } else if (item.options === "radio") {
          //由于checkIds 都是数组，radio类型下需要转化成字符串才可以
          form[item.sceneId] = item.checkIds.length > 0 ? item.checkIds[0] : "";
        }
        rules[item.sceneId] = [{ required: true, message: "请选择", trigger: "blur" }];
      });
      this.ruleForm = form;
      this.rules = rules;
    },
    //提交问卷
    subQuestion() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.saveQuestions();
          console.log(this.questionData);
          console.log(this.ruleForm);
          // this.$router.push("/evaluate/manage/1");
        } else {
          this.message.error({ message: "有必选项没选择" });
          // console.log("error submit!!");
          return false;
        }
      });
    },
    //提交选择的问卷 给后台一份
    saveQuestions() {
      saveQuestionsApi({ reportId: this.$route.query.reportId, answers: this.questionData }).then((res) => {
        console.log(res);
        this.message.success({ message: res.msg });
        this.$router.push({
          path: "evaluate/manage/detail",
          query: {
            id: this.$route.query.reportId,
            assetId: this.data.assetId,
          },
        });
      });
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.sign {
  font-size: 24px;
  color: $menuActiveText;
  float: left;
  line-height: 35px;
  margin-right: 10px;
  // font-weight: 600;
}
.question-main {
  width: 1100px;
  margin: 10px auto;
  position: relative;
}
.ruleForm {
  margin: 20px;
  padding-bottom: 15px;
  ::v-deep .el-form-item__label {
    font-size: 15px;
    padding-bottom: 0;
  }
  ::v-deep .el-checkbox-group,
  ::v-deep .el-radio-group,
  ::v-deep .el-form-item__error {
    margin-left: 40px;
  }
}
.question-sub-box {
  position: fixed;
  right: 50%;
  top: 100px;
  width: 310px;
  // height: 250px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #fff;
  border-radius: 4px;
  margin-right: -560px;
  // padding-bottom: 20px;
  .s-title {
    // height: 40px;
    // line-height: 40px;
    font-weight: 600;
    padding: 12px 0;
    color: #fff;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    text-align: center;
    background: $menuActiveText;
  }
}
.question-con {
  width: 760px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .title {
    position: relative;
    padding: 15px 0;
    text-align: center;
    font-weight: 600;
    font-size: 14px;
    color: #fff;
    background: $menuActiveText;
    border-bottom: 1px solid #e4e4e4;
    span {
      position: absolute;
      left: 10px;
      top: 50%;
      font-size: 14px;
      color: #fefefe;
      transform: translateY(-50%);
    }
  }
}
.sub-box_con {
  margin: 5px 15px 20px;
}
.sub-question_btn {
  margin: 10px;
  text-align: center;
}
.ul-box {
  overflow: hidden;
  margin: 10px 0;
  padding: 0;
  border-bottom: 1px dashed #eee;
  li {
    font-size: 12px;
    float: left;
    background: #ffffff;
    float: left;
    width: 22px;
    height: 22px;
    line-height: 22px;
    border: #cccccc 1px solid;
    border-radius: 3px;
    cursor: pointer;
    text-align: center;
    color: #666666;
    margin: 0px 6px 6px 0px;
    &.selected {
      background: $menuActiveText;
      color: #fff;
      border: 0;
    }
  }
}
.total {
  margin-bottom: 10px;
  span {
    color: red;
  }
}
.submit-que {
  width: 100%;
  border-radius: 0;
  font-size: 16px;
}
</style>
